//
//  PhotoManager.swift
//  googlypuff
//
//  Created by Open on 2/4/15.
//  Copyright (c) 2015 open-groupe. All rights reserved.
//

import UIKit
import Foundation

let PhotoManagerAddedContentNotification =
"com.open.learnGCD.PhotoManagerAddedContent"
let PhotoManagerContentUpdateNotification = "com.open.learnGCD.PhotoManagerContentUpdate"

typealias PhotoProcessingProcessClosure = (completionPrecentage: CGFloat) -> Void
typealias BatchPhotoDownloadingCompletionClosure = (error: NSError?) -> Void

private let _sharedManager = PhotoManager()

class PhotoManager {
    class var sharedManager: PhotoManager {
        return _sharedManager
    }
    
    private var _photos:[Photo] = []
    var photos: [Photo] {
        return _photos
    }
    
    func addPhoto(photo: Photo){
        _photos.append(photo)
        dispatch_async(dispatch_get_main_queue()) {
            self.postContentAddedNotification()
        }
    }
    
    func downloadPhotosWithCompletion(completion: BatchPhotoDownloadingCompletionClosure?)
    {
        var storedError: NSError?
        for address in [OverlyAttachedGirlfriendURLString,
            SuccessKidURLString,
            LotsOfFacesURLString
            ]{
               let url = NSURL(string: address)
                let photo = DownloadPhoto(url: url!){
                    image , error in
                    if error != nil
                    {
                        storedError = error
                    }
                }
                PhotoManager.sharedManager.addPhoto(photo)

        }
        if let completion = completion {
            completion(error: storedError)
        }
    }
    
    private func postContentAddedNotification()
    {
        NSNotificationCenter.defaultCenter().postNotificationName(PhotoManagerAddedContentNotification, object: nil)
    }
}






